// src/main/java/com/bookmanager/controller/BookController.java
package com.bookmanager.controller;

import com.bookmanager.model.Book;
import com.bookmanager.model.User;
import com.bookmanager.service.BookService;
import com.bookmanager.service.FavoriteService;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;


@WebServlet("/books")
public class BookController extends HttpServlet {
    private BookService bookService = new BookService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");

        String action = request.getParameter("action");
        List<Book> books;

        if ("search".equals(action)) {
            String keyword = request.getParameter("keyword");
            books = bookService.searchBooks(keyword);
            request.setAttribute("keyword", keyword);
        } else if ("edit".equals(action)) {
            showEditForm(request, response);
            return;
        } else {
            books = bookService.getAllBooks();
        }

        // 如果数据库没有数据，使用模拟数据测试
        if (books == null || books.isEmpty()) {
            books = createSampleBooks();
        }

        // 检查每本书的收藏状态
        if (user != null) {
            FavoriteService favoriteService = new FavoriteService();
            Map<Integer, Boolean> favoriteStatusMap = new HashMap<>();
            for (Book book : books) {
                boolean isFavorite = favoriteService.isBookFavorite(user.getUserId(), book.getBookId());
                favoriteStatusMap.put(book.getBookId(), isFavorite);
            }
            request.setAttribute("favoriteStatusMap", favoriteStatusMap);
        }

        request.setAttribute("books", books);
        request.getRequestDispatcher("book-list.jsp").forward(request, response);
    }

    private List<Book> createSampleBooks() {
        List<Book> books = new ArrayList<>();

        Book book1 = new Book();
        book1.setBookId(1);
        book1.setIsbn("9787111126768");
        book1.setTitle("Java编程思想");
        book1.setAuthor("Bruce Eckel");
        book1.setPublisher("机械工业出版社");
        book1.setPrice(new java.math.BigDecimal("89.00"));
        book1.setCategory("计算机");
        book1.setTotalCopies(5);
        book1.setAvailableCopies(3);
        book1.setStatus("available");
        books.add(book1);

        Book book2 = new Book();
        book2.setBookId(2);
        book2.setIsbn("9787115216878");
        book2.setTitle("Spring实战");
        book2.setAuthor("Craig Walls");
        book2.setPublisher("人民邮电出版社");
        book2.setPrice(new java.math.BigDecimal("79.00"));
        book2.setCategory("计算机");
        book2.setTotalCopies(3);
        book2.setAvailableCopies(0);
        book2.setStatus("borrowed");
        books.add(book2);

        return books;
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String action = request.getParameter("action");

        if ("add".equals(action)) {
            addBook(request, response);
        } else if ("update".equals(action)) {
            updateBook(request, response);
        } else if ("delete".equals(action)) {
            deleteBook(request, response);
        }
    }

    private void addBook(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Book book = new Book();
        book.setIsbn(request.getParameter("isbn"));
        book.setTitle(request.getParameter("title"));
        book.setAuthor(request.getParameter("author"));
        book.setPublisher(request.getParameter("publisher"));
        book.setPublishDate(LocalDate.parse(request.getParameter("publishDate")));
        book.setPrice(new BigDecimal(request.getParameter("price")));
        book.setCategory(request.getParameter("category"));
        book.setDescription(request.getParameter("description"));
        book.setTotalCopies(Integer.parseInt(request.getParameter("totalCopies")));
        book.setAvailableCopies(Integer.parseInt(request.getParameter("availableCopies")));
        book.setLocation(request.getParameter("location"));

        // 确保状态正确设置
        if (book.getAvailableCopies() > 0) {
            book.setStatus("available");
        } else {
            book.setStatus("borrowed");
        }

        if (bookService.addBook(book)) {
            response.sendRedirect("books?message=add_success");
        } else {
            response.sendRedirect("books?message=add_failed");
        }
    }

    private void updateBook(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            int bookId = Integer.parseInt(request.getParameter("bookId"));

            // 先获取现有的图书信息
            Book existingBook = bookService.getBookById(bookId);
            if (existingBook == null) {
                response.sendRedirect("books?message=update_failed&error=book_not_found");
                return;
            }

            // 创建更新后的图书对象
            Book book = new Book();
            book.setBookId(bookId);
            book.setIsbn(request.getParameter("isbn"));
            book.setTitle(request.getParameter("title"));
            book.setAuthor(request.getParameter("author"));
            book.setPublisher(request.getParameter("publisher"));

            // 处理出版日期（可能为空）
            String publishDateStr = request.getParameter("publishDate");
            if (publishDateStr != null && !publishDateStr.trim().isEmpty()) {
                book.setPublishDate(LocalDate.parse(publishDateStr));
            } else {
                book.setPublishDate(existingBook.getPublishDate());
            }

            // 处理价格
            String priceStr = request.getParameter("price");
            if (priceStr != null && !priceStr.trim().isEmpty()) {
                book.setPrice(new BigDecimal(priceStr));
            } else {
                book.setPrice(existingBook.getPrice());
            }

            book.setCategory(request.getParameter("category"));
            book.setDescription(request.getParameter("description"));

            // 处理总数量和可借数量
            String totalCopiesStr = request.getParameter("totalCopies");
            if (totalCopiesStr != null && !totalCopiesStr.trim().isEmpty()) {
                int totalCopies = Integer.parseInt(totalCopiesStr);
                book.setTotalCopies(totalCopies);

                // 自动计算可借数量（保持原有逻辑）
                String availableCopiesStr = request.getParameter("availableCopies");
                if (availableCopiesStr != null && !availableCopiesStr.trim().isEmpty()) {
                    book.setAvailableCopies(Integer.parseInt(availableCopiesStr));
                } else {
                    // 如果没有提供可借数量，根据总数量和状态自动计算
                    int borrowedCopies = existingBook.getTotalCopies() - existingBook.getAvailableCopies();
                    book.setAvailableCopies(Math.max(0, totalCopies - borrowedCopies));
                }
            } else {
                book.setTotalCopies(existingBook.getTotalCopies());
                book.setAvailableCopies(existingBook.getAvailableCopies());
            }

            book.setLocation(request.getParameter("location"));

            // 处理状态
            String status = request.getParameter("status");
            if (status != null && !status.trim().isEmpty()) {
                book.setStatus(status);
            } else {
                // 根据可借数量自动设置状态
                if (book.getAvailableCopies() > 0) {
                    book.setStatus("available");
                } else {
                    book.setStatus("borrowed");
                }
            }

            // 保留创建时间
            book.setCreateTime(existingBook.getCreateTime());

            if (bookService.updateBook(book)) {
                response.sendRedirect("books?message=update_success");
            } else {
                response.sendRedirect("books?message=update_failed");
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
            response.sendRedirect("books?message=update_failed&error=invalid_number");
        } catch (Exception e) {
            e.printStackTrace();
            response.sendRedirect("books?message=update_failed&error=system_error");
        }
    }

    private void showEditForm(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            int bookId = Integer.parseInt(request.getParameter("bookId"));
            Book book = bookService.getBookById(bookId);

            if (book != null) {
                request.setAttribute("book", book);
                request.getRequestDispatcher("book-edit.jsp").forward(request, response);
            } else {
                response.sendRedirect("books?message=book_not_found");
            }
        } catch (NumberFormatException e) {
            response.sendRedirect("books?message=invalid_book_id");
        }
    }

    private void deleteBook(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int bookId = Integer.parseInt(request.getParameter("bookId"));
        if (bookService.deleteBook(bookId)) {
            response.sendRedirect("books?message=delete_success");
        } else {
            response.sendRedirect("books?message=delete_failed");
        }
    }
}